package org.aceor.mddal.common.zk;

import org.aceor.mddal.common.zk.config.ConfigLoader;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by lxue on 16/3/19.
 */
public class ZKClient {
    private static final Logger logger = LoggerFactory.getLogger(ZKClient.class);
    private static volatile CuratorFramework zkClient;

    private ZKClient(){}

    public static CuratorFramework getClient(){
        if (null == zkClient) {
            synchronized (ZKClient.class) {
                if (null == zkClient) {
                    zkClient = CuratorFrameworkFactory.builder()
                            .connectString(ConfigLoader.getConnectString())
                            .sessionTimeoutMs(ConfigLoader.getSessionTimeout())
                            .retryPolicy(new ExponentialBackoffRetry(ConfigLoader.getBaseSleepTime(), ConfigLoader.getMaxRetries()))
                            .build();
                    zkClient.start();
                    logger.info("ZKClient$getClient ==> CuratorFramework ZKClient 启动成功!");
                }
            }
        }
        return zkClient;
    }
}
